import React from 'react';
import { connect } from 'react-redux';
import { withRouter } from 'react-router-dom';

import { List, Badge } from 'antd-mobile';

import { setRead } from '@/redux/modules/chatuser';

@connect(
    state => ({chatUser:state.chatUser, currentUser: state.user}),
    { setRead }
)
@withRouter
class Msg extends React.Component{
    getLast(arr = []){
        arr.sort((v1, v2) => {
            return v2.create_time - v1.create_time;
        })
        
        return arr;
    }
    render(){
        // get chat list
        const chats = this.props.chatUser;
        const ID = this.props.currentUser.userInfo.id;
        const filterChats = chats.msgs.filter(item => {return item.to === ID && !item.isRead});
        const groups = {};
        filterChats.forEach(v => {
            !groups[v.from] && (groups[v.from] = []);
            groups[v.from].push(v);
        });

        const chatList = Object.values(groups).sort((a, b) => {
            const alst = a[a.length -1],
                  blst = b[b.length - 1];
            
            return blst.create_time - alst.create_time;
        });

        /*if(filterChats.length){
            // get ids
            const ids = filterChats.filter((v) => v.isRead === false).map(item => {return item._id});
            ids.length && this.props.setRead(ids);
        }*/

        return (
            <List>
                {
                    chatList.map((item,i) => {
                        const news = this.getLast(item)[0];
                        return (
                            <List.Item 
                            arrow="horizontal"
                            extra={<Badge text={item.length}></Badge>}
                            onClick={() => {this.props.history.push(`/dashboard/chat/${news.from}`)}}
                            key={news._id}><img src={require(`@/component/avatarselector/img/${chats.users[news.from].tx}.png`)} alt='' />{chats.users[news.from].name}：{news.msg}</List.Item>
                        )
                    })
                }
                {
                    !chatList.length && <div>没有消息</div>
                }
            </List>
        );
    }
}

export default Msg;